<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Search, User, Lock, Message, ArrowDown } from '@element-plus/icons-vue'
import { login, register } from './api/auth'
import { ElMessage } from 'element-plus'
import { useUserStore } from './stores/user'
import { ElConfigProvider } from 'element-plus'
import zhCn from 'element-plus/dist/locale/zh-cn.mjs'
import Header from './components/Header.vue'

const router = useRouter()
const searchQuery = ref('')
const dialogVisible = ref(false)
const isLogin = ref(true)  // true 表示登录，false 表示注册

// 登录表单
const loginForm = reactive({
    username: '',
    password: ''
})

// 注册表单
const registerForm = reactive({
    username: '',
    password: '',
    confirmPassword: '',
    email: ''
})

const loading = ref(false)
const formRef = ref(null)

// 登录表单验证规则
const loginRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' }
    ]
}

// 注册表单验证规则
const registerRules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
    ],
    confirmPassword: [
        { required: true, message: '请确认密码', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                if (value !== registerForm.password) {
                    callback(new Error('两次输入密码不一致'))
                } else {
                    callback()
                }
            },
            trigger: 'blur'
        }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
    ]
}

const userStore = useUserStore()

const handleSearch = () => {
    // 实现搜索逻辑
}

const handleLogin = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                const res = await login(loginForm)
                if (res.code === 200) {
                    userStore.setToken(res.data)
                    await userStore.fetchCurrentUser()
                    ElMessage.success('登录成功')
                    dialogVisible.value = false
                    
                    // 检查是否有需要重定向的页面
                    const redirect = localStorage.getItem('redirect')
                    if (redirect) {
                        localStorage.removeItem('redirect')
                        router.push(redirect)
                    }
                } else {
                    ElMessage.error(res.message || '登录失败')
                }
            } catch (error) {
                console.error('Login error:', error)
                ElMessage.error(error.response?.data?.message || '登录失败')
            } finally {
                loading.value = false
            }
        }
    })
}

const handleRegister = async () => {
    if (!formRef.value) return
    
    await formRef.value.validate(async (valid) => {
        if (valid) {
            try {
                loading.value = true
                const { confirmPassword, ...registerData } = registerForm
                const res = await register(registerData)
                if (res.code === 200) {
                    ElMessage.success('注册成功')
                    isLogin.value = true  // 切换到登录表单
                } else {
                    ElMessage.error(res.message || '注册失败')
                }
            } catch (error) {
                console.error('Register error:', error)
                ElMessage.error(error.response?.data?.message || '注册失败')
            } finally {
                loading.value = false
            }
        }
    })
}

const resetForm = () => {
    if (formRef.value) {
        formRef.value.resetFields()
    }
}

const switchForm = () => {
    isLogin.value = !isLogin.value
    resetForm()
}

const handleLogout = () => {
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/')
}

// 在组件挂载时获取用户信息
onMounted(async () => {
    if (userStore.token) {
        await userStore.fetchCurrentUser()
    }
})
</script>

<template>
  <el-config-provider :locale="zhCn">
    <div class="app-container">
      <Header />
      <div class="main-content">
        <div class="content-wrapper">
          <router-view v-slot="{ Component }">
            <transition name="fade" mode="out-in">
              <component :is="Component" />
            </transition>
          </router-view>
        </div>
      </div>
    </div>
  </el-config-provider>
</template>

<style>
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

#app {
  min-height: 100vh;
  background-color: #f4f5f5;
}

.app-container {
  min-height: 100vh;
}

.main-content {
  padding-top: 20px; /* Header 的高度 */
  min-height: calc(100vh - 60px);
}

.content-wrapper {
  max-width: 1140px;
  margin: 0 auto;
  padding: 20px;
}

/* 响应式布局 */
@media screen and (max-width: 1200px) {
  .content-wrapper {
    max-width: 960px;
  }
}

@media screen and (max-width: 992px) {
  .content-wrapper {
    max-width: 720px;
  }
}

@media screen and (max-width: 768px) {
  .content-wrapper {
    max-width: 540px;
    padding: 16px;
  }
}

@media screen and (max-width: 576px) {
  .content-wrapper {
    padding: 12px;
  }
}
</style> 